#include "thread_pool.hpp"
#include "user.hpp"
#include "linked_list.hpp"
MYSQL *conn;
Zhuce lojin_msg;
static const uint16_t port = 8080;
int pipe_fd[2];
ListNode *userList = nullptr;
void func(int num)
{
    write(pipe_fd[1], "123", 3);
}
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc, 2);
    pipe(pipe_fd);
    pid_t pid = fork();
    if (pid > 0)
    {
        close(pipe_fd[0]);
        signal(2, func);
        wait(nullptr);
        close(pipe_fd[1]);
        printf("\nparent process exit.\n");
        exit(0);
    }
    close(pipe_fd[1]);
    setpgid(0, 0);
    threadpool_t threadpool;
    threadpoolInit(&threadpool, atoi(argv[1]));
    threadpoolStart(&threadpool);
    int listenfd = tcpInit("0.0.0.0", port);
    sql_connect(&conn); // 连接数据库
    int epfd = epoll_create(1);
    ERROR_CHECK(epfd, -1, "epoll create");
    epollAddReadFd(epfd, listenfd);
    epollAddReadFd(epfd, pipe_fd[0]);
    struct epoll_event *pEventArr = (struct epoll_event *)calloc(EVENT_ARR_SIZE,
                                                                 sizeof(struct epoll_event));
    while (true)
    {
        int ready = epoll_wait(epfd, pEventArr, EVENT_ARR_SIZE, -1);
        if (ready == -1 && errno == EINTR)
        {
            continue;
        }
        else if (ready == -1)
        {
            ERROR_CHECK(ready, -1, "epoll_wait");
        }
        else
        {
            for (int i = 0; i < ready; i++)
            {
                int fd = pEventArr[i].data.fd;
                if (fd == listenfd)
                {
                    int peerfd = accept(listenfd, nullptr, nullptr);
                    printf("\n conn %d has conneted.\n", peerfd);
                    epollAddReadFd(epfd, peerfd);
                    user_info_t *user = (user_info_t *)calloc(1, sizeof(user_info_t));
                    user->sockfd = peerfd;
                    appendNode(&userList, user);
                }
                else if (fd == pipe_fd[0])
                {
                    char buffer[128] = {0};
                    read(pipe_fd[0], buffer, sizeof(buffer));
                    threadpoolStop(&threadpool);
                    threadpoolDestroy(&threadpool);
                    close(listenfd);
                    close(epfd);
                    close(pipe_fd[0]);
                    printf("\nchild process exit.\n");
                    exit(0);
                }
                else
                {
                    handleMessage(fd, epfd, &threadpool.queue);
                }
            }
        }
    }
    return 0;
}